package org.zachary.agent.application;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.MailSendException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.retry.annotation.Recover;
import org.springframework.stereotype.Service;

import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;

import java.util.List;

@Slf4j
@Service
public class QQEmailService {

    @Resource
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;

    /**
     * 重试失败后发送报警邮件
     */
    @Recover
    public void recover(MailException e, String to, String subject, String htmlContent) {
        sendPlainTextMail("3314058754@qq.com", "邮件服务持续失败",
                "重试3次后仍无法发送至：" + to + "，错误为：" + e.getMessage());
    }

    /**
     * 发送 HTML 格式邮件（审核结果）
     */
    public void sendAuditResultEmail(String to, String name, String subjectName, boolean approved, String failedItems, String message) {
        String subject = "您的 " + subjectName + " 审核结果通知";
        String htmlContent;

        if (approved) {
            htmlContent = String.format("""
        <!DOCTYPE html>
        <html>
          <head>
            <meta charset="UTF-8" />
            <style>
              body {
                font-family: Arial, sans-serif;
                line-height: 1.6;
                color: #333;
                background-color: #f7f9fc;
                padding: 20px;
              }
              .container {
                background-color: #ffffff;
                border-radius: 8px;
                padding: 30px;
                max-width: 600px;
                margin: 0 auto;
                box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
              }
              .title {
                font-size: 20px;
                color: #1a56db;
                margin-bottom: 10px;
              }
              .content {
                font-size: 16px;
              }
              .footer {
                margin-top: 20px;
                font-size: 12px;
                color: #888;
              }
            </style>
          </head>
          <body>
            <div class="container">
              <div class="title">审核结果通知</div>
              <div class="content">
                <p>您好，<strong>%s</strong>：</p>
                <p>您提交的 <strong>" %s "</strong> 已审核通过。</p>
                <p>感谢您的耐心等待，欢迎继续使用我们的服务！</p>
              </div>
              <div class="footer">
                此邮件由系统自动发送，请勿回复。
              </div>
            </div>
          </body>
        </html>
        """, name, subjectName);
        } else {
            htmlContent = String.format("""
        <!DOCTYPE html>
        <html>
          <head>
            <meta charset="UTF-8" />
            <style>
              body {
                font-family: Arial, sans-serif;
                line-height: 1.6;
                color: #333;
                background-color: #f7f9fc;
                padding: 20px;
              }
              .container {
                background-color: #ffffff;
                border-radius: 8px;
                padding: 30px;
                max-width: 600px;
                margin: 0 auto;
                box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
              }
              .title {
                font-size: 20px;
                color: #e53935;
                margin-bottom: 10px;
              }
              .content {
                font-size: 16px;
              }
              .highlight {
                color: #d32f2f;
                font-weight: bold;
              }
              .footer {
                margin-top: 20px;
                font-size: 12px;
                color: #888;
              }
            </style>
          </head>
          <body>
            <div class="container">
              <div class="title">审核结果通知</div>
              <div class="content">
                <p>您好，<strong>%s</strong>：</p>
                <p>您提交的 <strong>%s</strong> 审核<span class="highlight">未通过</span>，请参考以下详情：</p>
                <p><strong>未通过项目：</strong> <span class="highlight">%s</span></p>
                <p><strong>管理员建议：</strong> %s</p>
              </div>
              <div class="footer">
                此邮件由系统自动发送，请勿回复。
              </div>
            </div>
          </body>
        </html>
        """, name, subjectName, failedItems, message);
        }


        try {
            sendHtmlMail(to, subject, htmlContent);
        } catch (MessagingException e) {
            log.error("发送审核邮件失败: {}", e.getMessage());
            throw new MailSendException("邮件发送失败", e);
        }
    }

    /**
     * 实际发送 HTML 邮件
     */
    public void sendHtmlMail(String to, String subject, String htmlContent) throws MessagingException {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(htmlContent, true); // HTML 格式
        mailSender.send(message);
        log.info("发送邮件成功 -> 收件人: {}, 标题: {}", to, subject);
    }

    /**
     * 备用纯文本邮件（报警使用）
     */
    public void sendPlainTextMail(String to, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);
        mailSender.send(message);
    }
}
